# Maintainer: Biswapriyo Nath <nathbappai@gmail.com>

_realname=rpi-imager
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.9.0
pkgrel=1
pkgdesc="Raspberry Pi Imaging Utility (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
msys2_references=(
  'archlinux: rpi-imager'
)
msys2_repository_url='https://github.com/raspberrypi/rpi-imager/'
url='https://www.raspberrypi.com/software'
license=('spdx:Apache-2.0')
depends=(
  "${MINGW_PACKAGE_PREFIX}-curl"
  "${MINGW_PACKAGE_PREFIX}-gcc-libs"
  "${MINGW_PACKAGE_PREFIX}-libarchive"
  "${MINGW_PACKAGE_PREFIX}-libwinpthread"
  "${MINGW_PACKAGE_PREFIX}-openssl"
  "${MINGW_PACKAGE_PREFIX}-qt6-base"
  "${MINGW_PACKAGE_PREFIX}-qt6-declarative"
  "${MINGW_PACKAGE_PREFIX}-xz"
  "${MINGW_PACKAGE_PREFIX}-zlib"
  "${MINGW_PACKAGE_PREFIX}-zstd"
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "${MINGW_PACKAGE_PREFIX}-qt6-svg"
  "${MINGW_PACKAGE_PREFIX}-qt6-tools"
  "${MINGW_PACKAGE_PREFIX}-winpthreads"
)
source=(
  "https://github.com/raspberrypi/rpi-imager/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
  0001-rpi-imager-cmake-disable-bundling.patch
  remove-vendoring.patch
)
noextract=("${_realname}-${pkgver}.tar.gz")
sha256sums=('ed0669b3e59c358a488ba0d23f1ffbbcb61f144ca37d6902a63276055838d694'
            '4e2813a3ee7ec455b46b554ac0661f6bb4e8c885ff8a1be2b742275123042b72'
            '81f969072be94494fd8938df850a3dcf71bda7b58268c45bc6b31ed3a79b0d9a')

_apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -p1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  tar -xf "${_realname}-${pkgver}.tar.gz" || true

  cd "${_realname}-${pkgver}"

  _apply_patch_with_msg \
    0001-rpi-imager-cmake-disable-bundling.patch

  # https://gitlab.archlinux.org/archlinux/packaging/packages/rpi-imager/-/blob/main/remove-vendoring.patch?ref_type=heads
  # with 'AND UNIX' condition removed
  _apply_patch_with_msg \
    remove-vendoring.patch
}

build() {
  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${_extra_config[@]}" \
      -DENABLE_CHECK_VERSION=OFF \
      -DENABLE_TELEMETRY=OFF \
      -DENABLE_VENDORING=OFF \
      -S "${_realname}-${pkgver}/src" \
      -B "build-${MSYSTEM}"

  cmake --build "build-${MSYSTEM}"
}

package() {
  install -Dm755 "build-${MSYSTEM}/rpi-imager.exe" "${pkgdir}${MINGW_PREFIX}/bin/rpi-imager.exe"
  install -Dm644 "${srcdir}/${_realname}-${pkgver}/license.txt" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/license.txt"
}
